package kr.hkit.androidcomplete02.ch19;

import kr.hkit.androidcomplete02.R;

import org.w3c.dom.Text;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class LooperEx extends Activity {
	int mMainValue = 0;
	TextView mMainText;
	TextView mBackText;
	EditText mEdit;
	CalThread thread;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch19_loopertest);
		mMainText = (TextView)findViewById(R.id.looper_mainvalue);
		mBackText = (TextView)findViewById(R.id.looper_backvalue);
		mEdit = (EditText)findViewById(R.id.looper_number);
		
		thread = new CalThread(mMainHandler);
		thread.setDaemon(true);
		thread.start();
	}
	
	public void mOnClick(View v){
		Message msg = null;
		
		switch(v.getId()){
		
		case R.id.looper_increase:
			mMainValue++;
			mMainText.setText("MainValue : " + mMainValue);
			break;
			
		case R.id.looper_square:
			msg = Message.obtain(thread.mBackHandler, 0, Integer.parseInt(mEdit.getText().toString()), 0);
			thread.mBackHandler.sendMessage(msg);
			break;
			
		case R.id.looper_root:
			msg = Message.obtain(thread.mBackHandler, 1, Integer.parseInt(mEdit.getText().toString()), 0);
			thread.mBackHandler.sendMessage(msg);
			break;
		}
	}
	
	
	Handler mMainHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			
			case 0:	// 제곱
				mBackText.setText("Square Result : " + msg.arg1);
				break;

			case 1:	// 제곱근
				mBackText.setText("Root Result : " + ((Double)(msg.obj)).doubleValue() );
				break;
				
			default:
				break;
			}
			//thread.mBackHandler.sendMessage(msg);
		}
		
	};
}

class CalThread extends Thread{
	Handler mMainHandler;
	Handler mBackHandler;
	
	public CalThread(Handler mMainHandler) {
		this.mMainHandler = mMainHandler;
	}

	@Override
	public void run() {
		Looper.prepare();		// 준비
		
		mBackHandler = new Handler(){
			// MainHandler에서 보낸 것을 받는다.
			@Override
			public void handleMessage(Message msg) {		// Main에서 보낸 Message
				//Message reMsg = Message.obtain();			// 내가 보낸 Message
				Message reMsg = null;
				
				switch(msg.what){
				
				// 제곱 계산
				case 0:
					reMsg = Message.obtain(mMainHandler, 0, msg.arg1 * msg.arg1, 0);
					//reMsg.what = 0;
					//reMsg.arg1 = msg.arg1 * msg.arg1;
					break;
				// 루트 계산	
					
				case 1:					
					reMsg = Message.obtain(mMainHandler, 1, new Double(Math.sqrt(msg.arg1)));
					// reMsg.what = 1;
					// reMsg.obj = new Double(Math.sqrt(msg.arg1));
					break;
				}
				
				mMainHandler.sendMessage(reMsg);
			}
			
		};
		Looper.loop();			// 반복
	}
	
	
	
}
